$(function () {

    $.fn.setCursorPosition = function(position){
        if(this.lengh == 0) return this;
        return $(this).setSelection(position, position);
    };

    $.fn.setSelection = function(selectionStart, selectionEnd) {
        if(this.lengh == 0) return this;
        input = this[0];

        if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        } else if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }

        return this;
    };

    $.fn.focusEnd = function(){
        this.setCursorPosition(this.val().length);
    };

    layui.use(['form','layer','element'],function () {

        //生成富文本编辑器
        var editor = new Simditor({
            textarea: $('#editor'),
            toolbar: [
                // 'bold',
                // 'italic',
                // 'underline',
                // 'strikethrough',
                'color',
                'emoji',
                // 'ol',
                // 'ul',
                'blockquote',
                'code',
                'link',
                'image',
                // 'hr',
                /*'indent',
                'outdent',*/
                // 'alignment'
            ],
            emoji: {
                imagePath: '/Public/simditor-emoji/images/emoji',
                images: [
                    /*'hbf2019_jinli_org.png',
                    '2018new_zhongguozan_org.png',*/
                    '2018new_erha_org.png',
                    /*'2018new_baobao_org.png',
                    '2018new_tanshou_org.png',
                    '2018new_gui_org.png',*/
                    '2018new_doge02_org.png',
                    '2018new_miaomiao_org.png',
                    '2018new_xiongmao_org.png',
                    '2018new_jiyan_org.png',
                    '2018new_xiaoku_thumb.png',
                    '2018new_qinqin_org.png',
                    '2018new_touxiao_org.png',
                    '2018new_kuxiao_org.png',
                    '2018new_xiaoerbuyu_org.png',
                    '2018new_haha_org.png',
                    '2018new_han_org.png',
                    '2018new_aini_org.png',
                    '2018new_chijing_org.png',
                    '2018new_dalian_org.png',
                    '2018new_chigua_org.png',
                    '2018new_chongjing_org.png',
                    '2018new_huaixiao_org.png',
                    '2018new_huaxin_org.png',
                    '2018new_yinxian_org.png',
                    '2018new_yun_org.png',
                    '2018new_zhouma_org.png',
                    '2018new_wenhao_org.png',
                    '2018new_wu_org.png',
                    '2018new_xixi_org.png',
                    '2018new_leimu_org.png',
                    '2018new_ku_org.png',
                    '2018new_kelian_org.png',
                    '2018new_beishang_org.png',
                    '2018new_chanzui_org.png',
                    '2018new_dahaqian_org.png',
                    '2018new_ningwen_org.png',
                    '2018new_nu_org.png',
                    '2018new_qian_org.png',
                    '2018new_shengbing_org.png',
                    '2018new_shuai_org.png',
                    '2018new_shuijiao_thumb.png',
                    '2018new_wabi_thumb.png',
                    '2018new_weiqu_org.png',
                    '2018new_zhuakuang_org.png',
                    '2018new_zuohengheng_org.png',
                    '2018new_youhengheng_org.png',
                    '2018new_heng_org.png',
                    '2018new_guzhang_org.png',
                    '2018new_heixian_org.png',
                    '2018new_tu_org.png',
                    '2018new_kouzhao_org.png',
                    '2018new_tianping_org.png',
                    '2018new_xianhua_org.png',
                ],
            },
            pasteImage: true,
            cleanPaste: true,
            upload: {
                url: '/BBS/uploadImage',
                params: null,
                fileKey: 'file',
                connectionCount: 3,
                leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
            },
            mention: {
                url: '/BBS/atUsers',
            }
        });

        var form = layui.form,
            layer = layui.layer,
            element = layui.element;

        // 点击回复，编辑器获取焦点，并定位到发表评论区域锚点
        $('.reply-focus').click(function() {
            editor.focus();
            $('html,body').animate({
                scrollTop: $('#reply').offset().top
            }, 'fast');
        });

        scroll($(document).scrollTop());

        $(document).scroll(function() {
            var scroH = $(document).scrollTop(); // 获取垂直滚动的距离
            scroll(scroH);
        });

        function scroll(scroH)
        {
            if (scroH >= 60) {
                //固定标题栏
                $('.bs-wp .b-head').addClass('b-head-fx');
                $('.anmao').css({top: '-135px'});
            } else {
                $('.bs-wp .b-head').removeClass('b-head-fx');
                $('.anmao').css({top: '-60px'});
            }

            if (scroH >= 210) {
                //固定热议榜
                $('.rt .bbs-ryb').addClass('fx');
            } else {
                $('.rt .bbs-ryb').removeClass('fx');
            }
        }

        // 收起/展开回复
        $('.fl').on('click', '.shrinkable-btn', function(e) {
            var count = $(this).attr('data-count');
            var i = $(this).find('i');
            if (i.hasClass('icon-angle-up')) {
                $(this).parent().next().hide();
                i.attr('class', 'icon-angle-down');
                $(this).removeClass('open');
                $(this).find('.shrinkable-txt').text('展开回复(' + count + ')');
            } else {
                $(this).parent().next().show();
                i.attr('class', 'icon-angle-up');
                $(this).addClass('open');
                $(this).find('.shrinkable-txt').text('收起回复(' + count + ')');
            }
        });

        // 我也说一句
        $('.fl .fl-body .rp-btn').unbind('click').on('click', function(e) {
            var rpBox = $(this).parents('.fl-body').find('.rp-box');
            var bid = $(this).attr('data-bid');     // 回复的BBS_id
            var lid = $(this).attr('data-lid');     // 回复的楼层id
            var uid = $(this).attr('data-uid');     // 回复的用户id
            var floor = $(this).attr('data-floor');     // 回复的用户id
            uid = typeof uid == 'undefined' ? '' : uid;
            var text = "";

            if (uid) {
                user = $(this).parent().parent().prev().find('span').eq(0).find('a').text();
                text = '回复 ' + user;
            }

            // 如果存在回复盒子
            if (rpBox.length) {
                rpBox.find('input[name="b_id"]').val(bid);
                rpBox.find('input[name="l_id"]').val(lid);
                rpBox.find('input[name="u_id"]').val(uid);
                rpBox.find('input[name="floor"]').val(floor);
                rpBox.find('textarea').val(text);
            } else {
                $('.lf .rp-box').remove();
                var html = '<div class="rp-box">';
                html += '<form action="/BBS/reply" method="post" class="layui-form">';
                html += '<input type="hidden" name="b_id" value="'+ bid +'"/>';
                html += '<input type="hidden" name="l_id" value="'+ lid +'"/>';
                html += '<input type="hidden" name="u_id" value="'+ uid +'"/>';
                html += '<input type="hidden" name="floor" value="'+ floor +'"/>';
                html += '<textarea class="form-control" rows="2" placeholder="回复内容" name="content">'+ text +'</textarea>';
                html += '<div class="text-right mt-10">' +
                    '<button type="button" class="btn btn-default btn-sm mr-10 cancel-reply">取 消</button>' +
                    '<button type="button" lay-submit lay-filter="reply" class="btn btn-primary btn-sm">回 复</button>' +
                    '</div>';
                html += '</form>';
                html += '</div>';
                $(html).insertAfter($(this).parents('.fl-body').find('.fl-footer'));

                // 插入后获取焦点
                $(this).parents('.fl-body').find('.rp-box textarea').focus();
                form.render();
            }

            // 将光标定位到最后
            $($(this).parents('.fl-body').find('.rp-box textarea')).focusEnd();
        });

        // 取消回复
        $('.lf .fl .fl-body').on('click', '.cancel-reply', function() {
            $(this).parents('.rp-box').remove();
        });

        // 楼层回复或楼中楼回复
        form.on('submit(reply)', function(data) {
            replyOrPublish(data.field);
        });

        // 发表
        form.on('submit(publish)', function(data) {
            replyOrPublish(data.field);
        });

        function replyOrPublish(data) {
            layer.load(2, {shade: [0.5, '#fff']});
            $.post('/BBS/reply', data, function(response) {
                if (response.flag) {
                    var floor = response.floor ? '#floor-' + response.floor : '';
                    location.href = '/BBS/show/id/' + response.id + '/p/' + response.pg;
                } else {
                    layer.closeAll();
                    layer.alert(response.msg, {icon: 0});
                }
            }, 'json');
        }

        // viewer图像预览插件
        $('.bs-wp .lf .fl-content').viewer();

        // 帖子管理操作
        $('#tzgl .pst-st').click(function(e) {
            e.preventDefault();
            var id = $(this).attr('data-id');
            var action = $(this).attr('data-action');
            var value = $(this).attr('data-val');

            var data = {id: id};

            if (action == 'top') {
                data.is_top = value;
            } else if (action == 'fine') {
                data.is_fine = value;
            }

            layer.load(2, {shade: [0.5, '#fff']});
            $.post('/BBS/management', data, function(response) {
                if (!response.code) {
                    location.reload();
                } else {
                    layer.closeAll();
                    layer.alert(response.msg);
                }
            }, 'json');
        });


        // 提交评论
        $('#submit-discuss-content').click(function (evt) {

            // 判断是否输入的空格 回车 空
            var strValue = editor.getValue();
            var string = strValue.replace(/\&nbsp\;/ig, ' ');

            if (!$.trim(string).length) {
                layer.msg('内容不能为空！', {icon: 2, time: 2000});
                return false;
            }

            // 拼装提交数据
            var result = {};
            result.content = editor.getValue();
            result.id = $('#submit-discuss-content').attr('discuss_id');
            result.count = $(this).attr('count');

            var loading = layer.load(2, {
                shade: [0.5, '#fff'] //0.1透明度的白色背景
            });

            $.ajax({
                url: '/BBS/reply',
                data: result,
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        SUB_NAME = response.id;
                        SUB_TYPE = response.type;
                        SUB_ID = response.flag;
                        PAGE = response.pg;
                        if (uploader.getFiles().length > 0) {
                            uploader.upload();
                        } else {
                            layer.msg(response.msg, {icon: 1, time: 2000});
                            setTimeout(function () {
                                location.href = '/BBS/show?id=' + response.id + '&p=' + response.pg + '&rd=' + Math.random().toString(36).substr(2) + '#comments';
                            }, 2000);
                        }
                    } else {
                        layer.msg(response.msg, {icon: 2, time: 2000});
                        setTimeout(function () {
                            layer.close(loading);
                        }, 2000);
                    }
                }
            })

        });


        $('.zan .thumbs-up').click(function () {
            var _this = $(this);
            $.post('/BBS/zan', {
                id: _this.attr('bbs-id')
            }, function(response) {
                if (!response.code) {
                    if (_this.hasClass('active')) {
                        _this.removeClass('active');
                    } else {
                        $('.WB_like').show();
                        _this.addClass('active');
                        setTimeout(function () {
                            $('.WB_like').hide();
                        }, 1000);
                    }

                    var html = zanUsers(response.data.users);
                    $('.zan-list').html(html);

                    $('.zan-count').html(response.data.count > 0 ? response.data.count : '');

                    $('.author-zan-count').html(response.data.authorZanCount);
                } else {
                    layer.alert(response.msg);
                }
            }, 'json');
        });

        //生成点赞用户显示的html
        function zanUsers(users)
        {
            var html = '';
            if (users.length) {
                html += '<i class="glyphicon glyphicon-thumbs-up thumbs-up active mr-10"></i>';
            }
            html += '<span class="zan-users">';
            for(var i = 0; i < users.length; i++) {
                if ((i + 1) == users.length) {
                    html += '<a href="javascript:;">' + users[i] + '</a>';
                } else {
                    html += '<a href="javascript:;">' + users[i] + '、</a>';
                }
            }
            html += '</span>';

            return html;
        }

        /**
         * 投票
         */
        //进度条测试数据
        var percentData = ['2/8','5/8','1/8'];
        $(".vote-show").find(".layui-progress-bar").each(function (i) {
            $(this).attr("lay-percent", percentData[i]);
        });
        element.init();

        //监听确定按钮
        form.on('submit(sure)',function (data) {
            //判断是否为空
            if ($.isEmptyObject(data.field)) {
                layer.msg('您没有勾选投票选项！', {icon: 2, time: 2000});
                return false; //不继续执行
            }
            //异步请求
            submitData(data.field);
            return false;
        });

        //点击取消按钮
        $(".layui-form .cancel").click(function () {
            //异步请求
            submitData('cancel');//告知后台此为取消操作，获取当前操作人，清除其上一步投票操作
            location.reload();//测试重新加载
        });

        //提交并重新渲染表单
        function submitData(data) {
            $.post("/Posts/post", data,function (response) {
                if (!response.code) {

                    //渲染参与投票成员显示
                    var html = voteUsers(response.data.users);
                    $('.vote-list').html(html);
                    $('.vote-count').html(response.data.count > 0 ? response.data.count : '');

                    //渲染投票后的进度条数据（选择该选项的人数/总的参与投票的人数）
                    var percentData = ['2/8','5/8','1/8']; //每一项的比例存入该数组
                    //进度条测试数据
                    $(".vote-show").find(".layui-progress-bar").each(function (i) {
                        $(this).attr("lay-percent", percentData[i]);
                    });
                    element.init();

                    //重新加载页面
                    location.reload();
                } else {
                    layer.msg(response.msg,{icon: 2,time:1000});
                }
            },'json');
        }

        //参与投票成员的展开or收起
        $('.vote-icon').click(function () {
            $('.vote-name').slideToggle();
        });

        //生成参与投票成员显示的html
        function voteUsers(users)
        {
            var html = '';
            if (users.length) {
                html += '<i class="icon-user vote-icon">参与投票成员(<span class="vote-count"></span>)</i>';
            }
            html += '<div class="vote-name pt-10" style="display: none"><span class="vote-users">';
            for(var i = 0; i < users.length; i++) {
                if ((i + 1) === users.length) {
                    html += '<a href="javascript:;">' + users[i] + '</a>';
                } else {
                    html += '<a href="javascript:;">' + users[i] + '、</a>';
                }
            }
            html += '</span></div>';

            return html;
        }

    });
});